import random
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from utils.form import RegisterModelForm, LoginModelForm
import redis
from utils.tencent.sms import send_sms_single


# Create your views here.

def send_sms(request):
    """ 发送短信 """
    '''
        ?tpl=login
        ?tpl=register
    '''
    tpl = request.GET.get('tpl')
    code = random.randrange(1000, 9999)
    template_id = settings.TEMPLATES[tpl]
    res = send_sms_single('19975275626', template_id, [code, ])
    print(res)
    return HttpResponse('success')


@csrf_exempt
def send_code(request):
    tpl = request.GET.get('tpl')
    phone = request.POST.get('phone')
    code = random.randrange(1000, 9999)
    # 连接redis
    conn = redis.Redis(host='127.0.0.1', port=6379, encoding='utf-8')
    conn.set(phone, code, ex=60)
    value = bytes.decode(conn.get(phone))
    print('value:', value)
    result = {
        'status': True,
        'code': value,
        'tpl': tpl
    }
    return JsonResponse(result)


def register(request):
    form = RegisterModelForm()
    if request.method == 'GET':
        return render(request, 'app01/register.html', {'form': form, 'title': '注 册'})

    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        print(form.cleaned_data)
        return HttpResponse('注册成功')
    return render(request, 'app01/register.html', {'form': form, 'title': '注 册'})


def login(request):
    form = LoginModelForm()
    if request.method == 'GET':
        return render(request, 'app01/register.html', {'form': form, 'title': '登 录'})

    form = LoginModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return HttpResponse('注册成功')
    return render(request, 'app01/register.html', {'form': form, 'title': '登 录'})
